package com.zsk.shop.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.service.schema.util.StringUtil;
import com.zsk.shop.common.base.BizException;
import com.zsk.shop.common.base.BizExceptionEnum;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.constant.RedisKeys;
import com.zsk.shop.common.base.model.token.TokenInfoModel;
import com.zsk.shop.common.base.model.token.UserSimple;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 快捷获取HttpServletRequest,HttpServletResponse
 *
 * @author Administrator
 */
@Slf4j
@Component
public class HttpContext {

    private static final Logger logger = LoggerFactory.getLogger(HttpContext.class);

    public static String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "";
        }
        final String authToken = requestAttributes.getRequest().getHeader("Authorization");
        return authToken;
    }

    public static String getDeviceToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "";
        }
        final String deviceToken = requestAttributes.getRequest().getHeader("deviceToken");
        return deviceToken;
    }

    public static Integer getPlatform() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return 0;
        }
        String platform = requestAttributes.getRequest().getHeader("platform");
        final Integer platformInt = ToolUtil.isEmpty(platform) ? 0 : Integer.parseInt(platform);
        return platformInt;
    }

    /**
     * 获取当前请求的Request对象
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        } else {
            return requestAttributes.getRequest();
        }
    }

    public static String getUserNo() {
        try {
            return TokenUtil.getToken().getUserNo();
        } catch (Exception e) {
            logger.info("token错误");
            throw new NoMsgException(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
        }
    }

    public static String getUserNo(String token) {
        if (StringUtil.isEmpty(token)) {
            logger.info("直接根据token获取用户userNo");
            return null;
        }
        try {
            TokenInfoModel tokenInfoModel = TokenUtil.verifyToken(token);
            return tokenInfoModel.getUserNo();
        } catch (Exception e) {
            logger.info("token错误：" + token);
            throw new NoMsgException(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage());
        }
    }

    public static String getSafeUserNo() {
        String userNo = null;
        try {
            userNo = TokenUtil.getToken().getUserNo();
        } catch (Exception e) {
        }
        return userNo;
    }

    /**
     * @param authToken
     * @return true-无效的token
     */
    public static boolean isTokenExpired(String authToken) {
        if (ToolUtil.isEmpty(authToken)) {
            return true;
        }
        try {
            UserSimple simple = getUser(authToken);
            if (ToolUtil.isEmpty(simple)) {
                return true;
            }
        } catch (Exception e) {
            logger.info("token处理失败" + getToken());
        }
        return false;
    }

    /**
     * 获取当前请求的Request对象
     */
    private static UserSimple getUser(String auth) {
        Object object;
        UserSimple simple = null;
        try {
            object = RedisUtil.getHashKey(RedisKeys.appUser.getHashKey(auth), auth);
            if (object != null) {
                simple = JSONObject.parseObject((String) object, UserSimple.class);
            }
        } catch (Exception e) {
            throw new BizException(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
        }
        return simple;
    }

    public static Long getSafeUserId() {
        Long userId = null;
        try {
            userId = TokenUtil.getToken().getId();
        } catch (Exception e) {
        }
        return userId;
    }

    public static Long getUserId() {
        Long userId = null;
        try {
            userId = TokenUtil.getToken().getId();
        } catch (Exception e) {
            logger.info("token错误");
            throw new NoMsgException(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
        }
        return userId;
    }
}
